/**********************************************************************
 * 
 * purpose: print a layer on the fly that  shows wps outputs   (bug 1623)        
 *
 * author:  Andrea Cappugi & Lorenzo Becchi 
 *
 * TODO:
 *   - all
 * 
 **********************************************************************
 *
 * Copyright (c)  2006, ominiverdi.org
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 * DEALINGS IN THE SOFTWARE.
 *
 **********************************************************************/

/******************************************************************************
 * wpsManager
 *
 * needs kaMap object
 *     
 *****************************************************************************/
function routerManager( oKaMap ) {
 	
	kaTool.apply( this, [oKaMap] );
    this.name = 'routerManager';
    //this.cursor = 'help';
	this.kaMap=oKaMap; 
	
	//WPS module params
	this.identifier= 'shortestpath2';
	this.map= this.kaMap.getCurrentMap().name;
	this.extent = this.kaMap.getCurrentMap().defaultExtents;
	this.wpsUrl = this.urlencode('http://pywps.ominiverdi.org/cgi-bin/wps.py');
	this.sldUrl = '';
	this.wpsCache=this.urlencode('/home/doktoreas/pywps.ominiverdi.org/subversion/trunk/web/tmp/');
	
	//internal vars
 	this.qId=0;
 	this.qLayer=null;
 	if (this.kaMap.sessionId) this.sessionId=this.kaMap.sessionId;
	else this.sessionId=null;
 	
	//create drawing canvas  for objects overlays 
	this.canvas = this.kaMap.createDrawingCanvas('10');
	//and tips as objects
	this.tipUrl = 'images/tip-yellow.png';
	this.tipUrl2 = 'images/tip-red.png';
	this.tipOffsetX = '-19px';// the negative left position of the pointer in the image
	this.tipOffsetY = '-6px';// the negative top position of the pointer in the image	
	
	
	//add SLD styles definitions 
	this.aSldURL = [];
	this.aSldURL.push(['Red color table',this.kaMap.server + 'tools/wps/sld/sld_red_table.php']);
	this.aSldURL.push(['Blue color table',this.kaMap.server + 'tools/wps/sld/sld_blue_table.php']);
	
	//Interface parameters
	this.aPoints = [];
	
	for (var p in kaTool.prototype) {
        if (!routerManager.prototype[p])
            routerManager.prototype[p]= kaTool.prototype[p];
    }
	
	this.interfaceInit();
};


/******************************************************************************
 * interfaceInit
 *
 * set up form fields

 *****************************************************************************/
routerManager.prototype.interfaceInit=function(){
 		//print ranges
				
				  
				
				
				
				
				//sld select
				var sldsel = getRawObject('routerSld');
				sldsel.onchange = this.setSldURL;
	
				var opt = new Option( 'select a sld', '', true, true );
				for(i=0;i<this.aSldURL.length;i++) {
					sldsel[i] = new Option(this.aSldURL[i][0],this.aSldURL[i][1],false,false);
					if(i==0)this.setSldURL();
				}
				
				
				//set button event
				getRawObject('routerCalc').onclick = this.query;
				getRawObject('routerCalc').visMan =  this;
				
};


/******************************************************************************
 * setWpsCache
 *
 * require path to wps cache dir
 *     
 *****************************************************************************/
routerManager.prototype.setWpsCache=function(dir){
 	this.wpsCache= dir;	
};
/******************************************************************************
 * setWpsURL
 *
 * require URL to WPS cgi executable
 *     
 *****************************************************************************/
routerManager.prototype.setWpsURL=function(url){
 	this.wpsUrl= url;	
};
/******************************************************************************
 * setWpsURL
 *
 * require URL to WPS cgi executable
 *     
 *****************************************************************************/
routerManager.prototype.setSldURL=function(){
	var sldsel = getRawObject('routerSld');
	var url =  sldsel.options[sldsel.selectedIndex].value;
	//var name = sldsel.options[sldsel.selectedIndex].innerHTML;
	getRawObject('routerSldLink').href = url;
 	this.sldUrl= url;	
};
/******************************************************************************
 * query
 *
 * needs map name,extents,identifier,datainputs. Then it prepares the call
 * to routerManager.php
 *****************************************************************************/
routerManager.prototype.query=function(){
	var visMan = this.visMan;
  
   var map =visMan.map;
   var extents= visMan.extent.join(',');
  	
	
	var input_x1= getRawObject('router_x1value').value;
	var input_y1 = getRawObject('router_y1value').value;
	var input_x2= getRawObject('router_x2value').value;
	var input_y2 = getRawObject('router_y2value').value;
	
	if(!(input_x1) || !(input_x2) || !(input_y1) || !(input_y2)){
		alert('Some values are null. Check your start and end point again.');
		return;
	}
	
	//BLOCCO QUI *********************************
	//alert('module not yet implemented. ciao!');
	//	return;
	//FINE BLOCCO QUI *********************************
	
	var datainputs = 'x1,'+input_x1+',y1,'+input_y1+',x2,'+input_x2+',y2,'+input_y2+',cost,0';
		
   if (visMan.kaMap.sessionId)  szSessionIdP="&sessionId="+visMan.kaMap.sessionId;
    else szSessionIdP="";
    
	
    
   var params="map="+map+szSessionIdP+"&id="+visMan.qId;
   params += "&extents="+extents+"&identifier="+visMan.identifier;
   params += "&datainputs="+datainputs;
   params += "&wpsCache="+visMan.wpsCache;
   params += "&wpsUrl="+visMan.urlencode(visMan.wpsUrl);
   params += "&sldUrl="+visMan.urlencode(visMan.sldUrl);
 	//alert(params);
 	//showContent('tools/query/routerManager.php?'+params);
   
  if (visMan.qLayer==null){
      visMan.createLayer();
    } else {
    for (i=0;i<visMan.qLayer.scales.length;i++)visMan.qLayer.scales[i]=1;
     visMan.qLayer.setVisibility( true );
     visMan.qLayer.setQueryable( true );
     visMan.kaMap.triggerEvent( KAMAP_SCALE_CHANGED, visMan.kaMap.getCurrentScale()); 
     visMan.qLayer.setLayer(visMan.identifier,visMan.qId);
    }
   call(visMan.kaMap.server + '/tools/wps/routerManager.php?'+params, visMan, visMan.queryResult);
  
};
/******************************************************************************
 * queryResult
 *
 * manage the ajax call output from query
 *     
 *****************************************************************************/
routerManager.prototype.queryResult=function(szResult ){
	if (szResult.substr(0, 1) != "/") {
        alert(szResult);
        return false;
    }
	//alert(szResult);
 	eval(szResult);
	
	if(queryResult==0){ 
		
       this.kaMap.sessionId  = this.sessionId;
	   var cMap = this.kaMap.getCurrentMap().name;
	   
	   this.kaMap.paintLayer(this.qLayer);	   
	   
	    //this.kaMap.triggerEvent( WPS_LAYER_PAINTING, 'wait for layer to be displayed' ); 
     	this.qId++;
		return true;
     	
     }else{
//     	if(this.kaMap.getCurrentMap().getLayer("queryLayer")) this.kaMap.removeMapLayer("queryLayer");
		alert("No results for this query!");
		return false;
	 }
 };
 /******************************************************************************
 * createLayer
 *
 * create a kaMap layer
 *     
 *****************************************************************************/
routerManager.prototype.createLayer=function(){
 	     
     if(this.identifier){
			this.qLayer= new _wpsLayer(this.identifier,true,100,'PNG',true,this.identifier,this.qId);
   			this.kaMap.addMapLayer(this.qLayer);
	} else alert('identifier not available');
	 //alert('layer to add:' +this.identifier);
 	 /*
     var legend=this.kaMap.getRawObject("group_wpsLayer");
     if(legend){
 		    
     var button= document.createElement('img');
     button.src=this.kaMap.server+"/images/legend_x.png";
     button.title="Remove Layer";
     button.alt="Remove Layer";
     button.qM=this;
     button.onclick = _queryManager_queryOnClick;
     legend.getElementsByTagName('tr')[0].appendChild(button);
     }*/
  
};
 /******************************************************************************
 * urlEncode
 *
 * encode a string as url
 *     
 *****************************************************************************/
routerManager.prototype.urlencode=function(string){
	encodedHtml = escape(string);
	encodedHtml = encodedHtml.replace("/","%2F");
	encodedHtml = encodedHtml.replace(/\?/g,"%3F");
	encodedHtml = encodedHtml.replace(/=/g,"%3D");
	encodedHtml = encodedHtml.replace(/&/g,"%26");
	encodedHtml = encodedHtml.replace(/@/g,"%40");
	return encodedHtml;
};

 /******************************************************************************
 * setFields
 *
 * set fields values in panel interface
 *     
 *****************************************************************************/
routerManager.prototype.setFields = function(gX,gY){
        //set input objects
        input_x = parseInt(gX);
		input_y = parseInt(gY);
		if(gX==null && gY==null){
	        getRawObject('router_x1value').value = null;
	        getRawObject('router_x1value_span').innerHTML = null;
	        getRawObject('router_y1value').value = null;
	        getRawObject('router_y1value_span').innerHTML = null;
			getRawObject('router_x2value').value = null;
	        getRawObject('router_x2value_span').innerHTML = null;
	        getRawObject('router_y2value').value = null;
	        getRawObject('router_y2value_span').innerHTML = null;
			return;
		}
		
		if(this.aPoints.length==1){
	        getRawObject('router_x1value').value = input_x;
	        getRawObject('router_x1value_span').innerHTML = input_x;
	        getRawObject('router_y1value').value = input_y;
	        getRawObject('router_y1value_span').innerHTML = input_y;
		} else if (this.aPoints.length==2){
			getRawObject('router_x2value').value = input_x;
	        getRawObject('router_x2value_span').innerHTML = input_x;
	        getRawObject('router_y2value').value = input_y;
	        getRawObject('router_y2value_span').innerHTML = input_y;
		} 
};


/******************************************************************************
 * onmousedown
 *
 * handle mouse down events.  Start tracking mouse movement for panning.
 * @param {Event} e the mouse event object
 *****************************************************************************/

routerManager.prototype.onmousedown = function(e) {
    e = (e)?e:((event)?event:null);
    if (e.button==2) {
        return this.cancelEvent(e);
    } else {
		this.cursor = this.cursorDrag;
    	this.kaMap.setCursor(this.cursorDrag);
        if (this.kaMap.isIE4) {
            document.onkeydown = kaTool_redirect_onkeypress;
        }
        document.onkeypress = kaTool_redirect_onkeypress;
        
        this.bMouseDown=true;
        var x = e.pageX || (e.clientX +
             (document.documentElement.scrollLeft || document.body.scrollLeft));
        var y = e.pageY || (e.clientY +
             (document.documentElement.scrollTop || document.body.scrollTop));
        this.lastx=x;
        this.lasty=y;
        this.startx = this.lastx;
        this.starty = this.lasty;
        
        e.cancelBubble = true;
        e.returnValue = false;
        if (e.stopPropogation) e.stopPropogation();
        if (e.preventDefault) e.preventDefault();
        return false;
    }
};

var gDblClickTimer = null;

/******************************************************************************
 * onmouseup
 *
 * handle the mouse up events.  Stop tracking mouse movement.
 * @param {Event} e the mouse event object
 *****************************************************************************/

routerManager.prototype.onmouseup = function(e) {
	this.cursor = this.cursorNormal;
    this.kaMap.setCursor(this.cursorNormal);
	
    e = (e)?e:((event)?event:null);
    this.bMouseDown=false;
    var x = e.pageX || (e.clientX +
        (document.documentElement.scrollLeft || document.body.scrollLeft));
    var y = e.pageY || (e.clientY +
        (document.documentElement.scrollTop || document.body.scrollTop));
    if (Math.abs(x-this.startx) < 2 &&
        Math.abs(y-this.starty) < 2) {
        if (!gDblClickTimer) {
            gDblClickTimer = window.setTimeout(bind(this.dispatchMapClicked, this, x, y), 250);
        }
    } else {
        gDblClickTimer = null;
        this.kaMap.showLayers();
        this.kaMap.triggerEvent(KAMAP_EXTENTS_CHANGED, this.kaMap.getGeoExtents());        
    }
    return false;
};

/******************************************************************************
 * dispatchMapClicked
 *
 * do something on single click with this tool active
 *****************************************************************************/

routerManager.prototype.dispatchMapClicked = function(px,py) {
    var a = this.adjustPixPosition( px,py );
    var p = this.kaMap.pixToGeo( a[0],a[1] );
    gDblClickTimer=null;
    //this.kaMap.triggerEvent(KAMAP_MAP_CLICKED, p);
	
	if(this.aPoints.length<2){
		this.aPoints.push(p);
	} else {
		this.aPoints = [];
		//empty pins
		this.kaMap.removeAllObjects(this.canvas);
		this.setFields(null,null);
		return;
	}
	
			//set values in panel fields
			this.setFields(p[0],p[1]);
			
			
			//create the pin obj
			var pinDiv = document.createElement('div');
			pinDiv.id = 'pinDiv';
			var pinImg = document.createElement('img');
			if(this.aPoints.length==1) pinImg.src = this.tipUrl;
			if(this.aPoints.length==2) pinImg.src = this.tipUrl2;
			pinImg.style.position = 'absolute';
			pinImg.style.top = this.tipOffsetX;
			pinImg.style.left = this.tipOffsetY;
			pinDiv.appendChild(pinImg);
			myKaMap.addObjectGeo( this.canvas, p[0], p[1], pinDiv );
};